import { login, logout, getInfo } from '@/api/login'
import {setToken} from '@/utils/auth'
const user={
    state:{
        token:'',
        userId:'',
        name:'',
        avatar: '',
        roles: [],
        nav:[]
    },
    mutations:{
        LOG_OUT: (state) => {
            localStorage.setItem('token', '')
            localStorage.setItem('name', '')
            state = {
                token:'',
                userId:'',
                name:'',
                avatar: '',
                roles: [],
                nav:[]
            }
        },
        SET_TOKEN: (state, token) => {
            state.token = token
            setToken(token)
            // localStorage.setItem('token', token)
        },
        SET_USER_ID: (state, token) => {
            var arr = token.split('|')
            state.userId = token
            localStorage.setItem('userId', arr[2])
        },
        SET_NAME: (state, name) => {
            state.name = name
            localStorage.setItem('name', name)
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
            localStorage.setItem('roles', roles)
        },
        SET_NAV: (state, nav) => {
            state.nav = nav
            localStorage.setItem('nav', nav)
        },
    },

    actions:{
        // 登录
        Login({ commit }, userInfo) {
            const user_name = userInfo.user_name.trim()
            return new Promise((resolve, reject) => {
                login(user_name, userInfo.password, userInfo.vcode).then(response => {
                    const data = response
                    commit('SET_TOKEN', data.token)
                    commit('SET_USER_ID', data.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })

            })
        },

        // 登出
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                /*logout(getUserId()).then(() => {
                    commit('LOG_OUT')
                    resolve()
                }).catch(error => {
                    reject(error)
                })*/
            })
        },

        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('LOG_OUT')
                resolve()
            })
        }
    }
}

export default user
